package com.yang.yangCommand;

import com.yang.YangMonster;
import com.yang.entity.Drop;
import com.yang.entity.Enchant;
import com.yang.entity.Monster;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class MonsterController implements Listener {

    private YangMonster yangMonster;

    public MonsterController(YangMonster yangMonster) {
        this.yangMonster = yangMonster;
        loadConfig();
    }

    private static FileConfiguration yaml;

    private int num = 0;

    // 获取到Config
    public void loadConfig() {
        yaml = yangMonster.getConfig();
        loadConfigMonster();
        num += 1;
        yangMonster.log(ChatColor.RED, "加载: [第" + num + "次]加载怪物列表成功");
        startCheckTask();
    }



    //加载yml怪物列表
    public void loadConfigMonster() {
        //先加载yml一级monster
        ConfigurationSection monster = yangMonster.getConfig().getConfigurationSection("monster");
        // 一级不为空的话
        if (monster != null) {
            // 获取所有二级
            Set<String> monsterKeys = monster.getKeys(false);
            // 循环二级key monster1 monster2
            for (String monsterKey : monsterKeys) {
                // 创建个实体类
                Monster entityMonster = new Monster();
                // 拿到二级里面的三级
                ConfigurationSection currentMonster = monster.getConfigurationSection(monsterKey);
                entityMonster.setName(currentMonster.getString("name"));
                entityMonster.setType(currentMonster.getString("type"));
                entityMonster.setLevel(currentMonster.getInt("level"));
                entityMonster.setHp(currentMonster.getDouble("hp"));
                entityMonster.setItem(currentMonster.getString("item"));
                entityMonster.setItemName(currentMonster.getString("itemName"));
                //拿到附魔所有属性
                // 三级里面写死的key
                ConfigurationSection itemEnchant = currentMonster.getConfigurationSection("itemEnchant");
                // 获取三级里面的四级所有
                Set<String> itemEnchantKeys = itemEnchant.getKeys(false);
                // 创建一个List
                List<Enchant> enchantList = new ArrayList<>();
                // 循环四级的key enchant1 enchant2
                itemEnchantKeys.forEach(v -> {
                    // 拿到四级里面五级
                    ConfigurationSection itemEnchantSection = itemEnchant.getConfigurationSection(v);
                    // 把五级存入进去 type name
                    enchantList.add(
                            new Enchant(
                                    itemEnchantSection.getString("type"),
                                    itemEnchantSection.getInt("level")
                            )
                    );
                });
                entityMonster.setItemEnchant(enchantList);

                // 拿到所有掉落信息
                // 三级里面写死的key
                ConfigurationSection drop = currentMonster.getConfigurationSection("drop");
                // 获取三级里面的四级所有
                Set<String> dropKeys = drop.getKeys(false);
                // 创建一个List
                List<Drop> dropList = new ArrayList<>();
                // 循环四级的key drop1 drop2
                dropKeys.forEach(v -> {
                    // 拿到四级里面五级
                    ConfigurationSection dropSection = drop.getConfigurationSection(v);
                    // 把五级存入进去 type name
                    dropList.add(
                            new Drop(
                                    dropSection.getString("name"),
                                    dropSection.getString("type"),
                                    dropSection.getString("enchant"),
                                    dropSection.getInt("enchantLevel"),
                                    dropSection.getInt("num"),
                                    dropSection.getInt("odds"),
                                    dropSection.getInt("min"),
                                    dropSection.getInt("max"),
                                    dropSection.getString("lore")
                            )
                    );
                });
                entityMonster.setDrop(dropList);
                entityMonster.setTag(currentMonster.getString("tag"));
                entityMonster.setWorld(currentMonster.getString("world"));
                entityMonster.setX(currentMonster.getInt("x"));
                entityMonster.setY(currentMonster.getInt("y"));
                entityMonster.setZ(currentMonster.getInt("z"));
                entityMonster.setNum(currentMonster.getInt("num"));
                entityMonster.setTime(currentMonster.getInt("time"));
                entityMonster.setRadius(currentMonster.getInt("radius"));
                // 添加到怪物列表
                monsterList.add(entityMonster);
                tagList.add(entityMonster.getTag());
            }
        }
    }

    //怪物集合
    private List<Monster> monsterList = new ArrayList<>();

    //自定义怪物Tag
    private List<String> tagList = new ArrayList<>();

    // 启动定时任务
    public void startCheckTask() {
        for (Monster monster : monsterList) {
            final Monster currentMonster = monster; // 创建 final 副本
            BukkitRunnable task = new BukkitRunnable() {
                @Override
                public void run() {
                    // 每隔一定时间执行检查玩家位置的任务
                    saveMaterial(currentMonster);
                }
            };
            task.runTaskTimer(yangMonster, 0, monster.getTime() * 20);
        }
    }

    //生成怪物
    public void saveMaterial(Monster monster) {
        // 根据此怪物附近有没有玩家生成怪物
        if (checkPlayersNearCustomArea(monster.getX(), monster.getZ(), monster.getRadius(), monster.getTag())) {
            for (int i = 0; i < monster.getNum(); i++) {
                //怪物手持物品
                ItemStack itemStack = new ItemStack(Material.getMaterial(monster.getItem())); // 用你想要的物品替换 Diamond Sword
                // 你可以设置物品的元数据，例如名称、附魔等
                ItemMeta meta = itemStack.getItemMeta();
                meta.setDisplayName(monster.getItemName());
                monster.getItemEnchant().forEach(v -> {
                    // 添加附魔
                    Enchantment enchantment = Enchantment.getByName(v.getType()); // 以伤害附魔为例
                    meta.addEnchant(enchantment, v.getLevel(), true); // 将附魔添加到物品元数据中
                });
                // 应用物品元数据
                itemStack.setItemMeta(meta);
                //设置此物品攻击伤害
                // 生成怪物
                //生成世界
                World world = yangMonster.getServer().getWorld(monster.getWorld()); // 替换为你希望生成生物的世界名称
                EntityType entityType = EntityType.fromName(monster.getType());
                Location location = new Location(world, monster.getX(), monster.getY(), monster.getZ()); // 使用获取的坐标位置
                //怪物类型
                LivingEntity entity = (LivingEntity) world.spawnEntity(location, entityType);
                //添加标签
                entity.addScoreboardTag(monster.getTag());
                //血量
                entity.setMaxHealth(monster.getHp());
                entity.setHealth(monster.getHp());
                entity.setAI(true);
                entity.setCustomNameVisible(true);
                entity.setCustomName(monster.getName());
                //手持物品
                entity.getEquipment().setItemInMainHand(itemStack);
            }
        }
    }

    // 检查玩家是否在指定区域附近
    public boolean isPlayerNearCustomArea(Location location, Integer x, Integer y, Integer radius) {
        // 指定的区域位置为 X 轴 -234，Z 轴 233，Y 轴 0-255（整个高度范围）
        int centerX = x;
        int centerZ = y;
        //获取 X 组件的下限值，指示包含此位置的块。
        int playerX = location.getBlockX();
        int playerZ = location.getBlockZ();
        // 检查玩家 X 和 Z 轴坐标是否在指定范围内
        return Math.abs(playerX - centerX) <= radius && Math.abs(playerZ - centerZ) <= radius;
    }


    // 检查玩家是否在指定区域附近
    public Boolean checkPlayersNearCustomArea(Integer x, Integer y, Integer radius, String tag) {
        // 所在玩家数量
        int playerNum = 0;
        for (Player player : Bukkit.getOnlinePlayers()) {
            Location playerLocation = player.getLocation();
            if (isPlayerNearCustomArea(playerLocation, x, y, radius)) {
                playerNum += 1;
            }
        }
        if (playerNum > 0) {
            return true;
        } else {
            // 查找拥有特定标签的怪物实体并将其删除
            for (World world : Bukkit.getWorlds()) {
                for (Entity entity : world.getEntities()) {
                    if (entity instanceof LivingEntity && entity.getScoreboardTags().contains(tag)) {
                        entity.remove();
                    }
                }
            }
        }
        return false;
    }


    //清空怪物默认 掉落物
    @EventHandler
    public void onEntityDeath(EntityDeathEvent event) {
        List<ItemStack> customDrops = new ArrayList<>(); // 用于存储所有掉落物
        LivingEntity entity = event.getEntity();
        // 掉落率
        Random random = new Random();
        for (Monster monster : monsterList) {
            if (isYourCustomCreature(entity, monster.getTag())) {
                //获得物品的meta
                event.getDrops().clear(); // 清除默认掉落
                for (Drop drop : monster.getDrop()) {
                    int dorpRandom = random.nextInt(drop.getMax() - drop.getMin() + 1) + drop.getMin();
                    if (dorpRandom > drop.getOdds()) {
                        //掉落物名字
                        ItemStack customDrop = new ItemStack(Material.getMaterial(drop.getType())); // 举例：自定义掉落物品为钻石
                        ItemMeta itemMeta = customDrop.getItemMeta();
                        itemMeta.setDisplayName(drop.getName());
                        List<String> stringList = new ArrayList<>();
                        stringList.add(drop.getLore());
                        itemMeta.setLore(stringList);
                        customDrop.setAmount(drop.getNum());
                        customDrop.setItemMeta(itemMeta);
                        customDrop.addUnsafeEnchantment(Enchantment.getByName(drop.getEnchant()), drop.getEnchantLevel());
                        customDrops.add(customDrop);
                    } else {
                        // 检查实体死亡时的最后一次伤害事件
                        EntityDamageEvent lastDamageCause = entity.getLastDamageCause();
                        if (lastDamageCause instanceof EntityDamageByEntityEvent) {
                            EntityDamageByEntityEvent entityDamageEvent = (EntityDamageByEntityEvent) lastDamageCause;
                            Entity damager = entityDamageEvent.getDamager();
                            // 检查造成伤害的实体是玩家
                            if (damager instanceof Player) {
                                Player player = (Player) damager;

                                // 在这里可以执行逻辑，针对特定玩家进行操作
                                player.sendMessage(ChatColor.YELLOW + " 你击败了" + monster.getName() + "但是它没掉落"+ drop.getName() +"物品，你的运气真差！");
                            }
                        }
                    }
                }
            }
        }
        event.getDrops().addAll(customDrops);

    }


    // 自定义方法用于检查实体是否是你创建的生物类型
    public boolean isYourCustomCreature(LivingEntity entity, String tag) {
        return entity.getScoreboardTags().contains(tag);
    }


}
